chia-blockchain/chia/daemon/keychain_proxy.py

452 lines
18 KiB
Python
Raw Normal View History

from __future__ import annotations
import asyncio
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
import logging
import ssl
import traceback
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
from aiohttp import ClientConnectorError, ClientSession
from chia_rs import AugSchemeMPL, PrivateKey
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
from chia.cmds.init_funcs import check_keys
from chia.daemon.client import DaemonProxy
from chia.daemon.keychain_server import (
KEYCHAIN_ERR_KEY_NOT_FOUND,
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
KEYCHAIN_ERR_KEYERROR,
KEYCHAIN_ERR_LOCKED,
KEYCHAIN_ERR_MALFORMED_REQUEST,
KEYCHAIN_ERR_NO_KEYS,
)
from chia.server.server import ssl_context_for_client
from chia.util.config import load_config
from chia.util.errors import (
KeychainIsEmpty,
KeychainIsLocked,
KeychainKeyNotFound,
KeychainMalformedRequest,
KeychainMalformedResponse,
KeychainProxyConnectionTimeout,
)
from chia.util.keychain import Keychain, KeyData, bytes_to_mnemonic, mnemonic_to_seed
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
from chia.util.ws_message import WsRpcMessage
class KeychainProxy(DaemonProxy):
"""
KeychainProxy can act on behalf of a local or remote keychain. In the case of
wrapping a local keychain, the proxy object simply forwards-along the calls to
the underlying local keychain. In the remote case, calls are made to the daemon
over the RPC interface, allowing the daemon to act as the keychain authority.
"""
def __init__(
self,
log: logging.Logger,
uri: str = "",
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
ssl_context: Optional[ssl.SSLContext] = None,
local_keychain: Optional[Keychain] = None,
user: Optional[str] = None,
service: Optional[str] = None,
heartbeat: int = 300,
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
):
super().__init__(uri, ssl_context, heartbeat=heartbeat)
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
self.log = log
if local_keychain:
self.keychain = local_keychain
else:
self.keychain = None # type: ignore
self.keychain_user = user
macOS keyring.yaml support (#8292) * Added 'service' as a Keychain ctor param. Removed 'testing' * Detect existing keys in the Mac Keychain * Fix to allow migration of keys on macOS * Added dump_keyring.py tool to show decrypted contents of keyring.yaml * Prompt to save passphrase to macOS keychain * Master passphrase retrieval/removal from the macOS Keychain. Fixed typos. * Warn if errSecInteractionNotAllowed is detected when accessing the macOS Keychain * Fixed file_keyring synchronization test failures on macOS. Fixed sporadic test failures on macOS when fsevents are delivered for the keyring after deletion. TempKeyring-based tests now patch supports_os_passphrase_storage() to return False. * TempKeyring mocks-out legacy_keyring setup to allow tests to succeed on macOS (which could find existing keys in the Keychain) * Fixed pylint error * Use with_name instead of with_stem (which is new to Python 3.9) * Fixed keychain tests that started prompting for the keyring passphrase. * Fixed LGTM issues * Re-added the cleaning up temp keychain statement. This is being removed in a separate PR. * Linter fixes * Fixed keyring assignment on macOS when passphrase support is disabled. * Include 'can_save_passphrase' flag in keyring_status response * More linter fixes * Fixed determination of the user_passphrase_is_set flag. This was returning true for a newly created keyring without any keys (or passphrase set) * Removed the tidy_passphrase function per feedback * Added some comments based on feedback * Update chia/cmds/passphrase_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com>
2021-09-24 20:32:57 +03:00
self.keychain_service = service
# these are used to track and close the keychain connection
self.keychain_connection_task: Optional[asyncio.Task[None]] = None
self.shut_down: bool = False
self.connection_established: asyncio.Event = asyncio.Event()
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
def use_local_keychain(self) -> bool:
"""
Indicates whether the proxy forwards calls to a local keychain
"""
return self.keychain is not None
def format_request(self, command: str, data: Dict[str, Any]) -> WsRpcMessage:
"""
Overrides DaemonProxy.format_request() to add keychain-specific RPC params
"""
if data is None:
data = {}
macOS keyring.yaml support (#8292) * Added 'service' as a Keychain ctor param. Removed 'testing' * Detect existing keys in the Mac Keychain * Fix to allow migration of keys on macOS * Added dump_keyring.py tool to show decrypted contents of keyring.yaml * Prompt to save passphrase to macOS keychain * Master passphrase retrieval/removal from the macOS Keychain. Fixed typos. * Warn if errSecInteractionNotAllowed is detected when accessing the macOS Keychain * Fixed file_keyring synchronization test failures on macOS. Fixed sporadic test failures on macOS when fsevents are delivered for the keyring after deletion. TempKeyring-based tests now patch supports_os_passphrase_storage() to return False. * TempKeyring mocks-out legacy_keyring setup to allow tests to succeed on macOS (which could find existing keys in the Keychain) * Fixed pylint error * Use with_name instead of with_stem (which is new to Python 3.9) * Fixed keychain tests that started prompting for the keyring passphrase. * Fixed LGTM issues * Re-added the cleaning up temp keychain statement. This is being removed in a separate PR. * Linter fixes * Fixed keyring assignment on macOS when passphrase support is disabled. * Include 'can_save_passphrase' flag in keyring_status response * More linter fixes * Fixed determination of the user_passphrase_is_set flag. This was returning true for a newly created keyring without any keys (or passphrase set) * Removed the tidy_passphrase function per feedback * Added some comments based on feedback * Update chia/cmds/passphrase_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com>
2021-09-24 20:32:57 +03:00
if self.keychain_user or self.keychain_service:
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
data["kc_user"] = self.keychain_user
macOS keyring.yaml support (#8292) * Added 'service' as a Keychain ctor param. Removed 'testing' * Detect existing keys in the Mac Keychain * Fix to allow migration of keys on macOS * Added dump_keyring.py tool to show decrypted contents of keyring.yaml * Prompt to save passphrase to macOS keychain * Master passphrase retrieval/removal from the macOS Keychain. Fixed typos. * Warn if errSecInteractionNotAllowed is detected when accessing the macOS Keychain * Fixed file_keyring synchronization test failures on macOS. Fixed sporadic test failures on macOS when fsevents are delivered for the keyring after deletion. TempKeyring-based tests now patch supports_os_passphrase_storage() to return False. * TempKeyring mocks-out legacy_keyring setup to allow tests to succeed on macOS (which could find existing keys in the Keychain) * Fixed pylint error * Use with_name instead of with_stem (which is new to Python 3.9) * Fixed keychain tests that started prompting for the keyring passphrase. * Fixed LGTM issues * Re-added the cleaning up temp keychain statement. This is being removed in a separate PR. * Linter fixes * Fixed keyring assignment on macOS when passphrase support is disabled. * Include 'can_save_passphrase' flag in keyring_status response * More linter fixes * Fixed determination of the user_passphrase_is_set flag. This was returning true for a newly created keyring without any keys (or passphrase set) * Removed the tidy_passphrase function per feedback * Added some comments based on feedback * Update chia/cmds/passphrase_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com>
2021-09-24 20:32:57 +03:00
data["kc_service"] = self.keychain_service
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
return super().format_request(command, data)
async def _get(self, request: WsRpcMessage) -> WsRpcMessage:
"""
Overrides DaemonProxy._get() to handle the connection state
"""
try:
if not self.shut_down: # if we are shut down, and we send a request we should throw original error.
await asyncio.wait_for(self.connection_established.wait(), timeout=30) # in case of heavy swap usage.
else:
self.log.error("Attempting to send request to a keychain-proxy that has shut down.")
self.log.debug(f"Sending request to keychain command: {request['command']} from {request['origin']}.")
return await super()._get(request)
except asyncio.TimeoutError:
raise KeychainProxyConnectionTimeout()
async def start(self) -> None:
self.keychain_connection_task = asyncio.create_task(self.connect_to_keychain())
await self.connection_established.wait() # wait until connection is established.
async def connect_to_keychain(self) -> None:
while not self.shut_down:
try:
self.client_session = ClientSession()
self.websocket = await self.client_session.ws_connect(
self._uri,
autoclose=True,
autoping=True,
heartbeat=self.heartbeat,
ssl=self.ssl_context,
max_msg_size=self.max_message_size,
)
await self.listener()
except ClientConnectorError:
self.log.warning(f"Can not connect to keychain at {self._uri}.")
except Exception as e:
tb = traceback.format_exc()
self.log.warning(f"Exception: {tb} {type(e)}")
self.log.info(f"Reconnecting to keychain at {self._uri}.")
self.connection_established.clear()
if self.websocket is not None:
await self.websocket.close()
if self.client_session is not None:
await self.client_session.close()
self.websocket = None
self.client_session = None
await asyncio.sleep(2)
async def listener(self) -> None:
self.connection_established.set() # mark connection as active.
await super().listener()
self.log.info("Close signal received from keychain, we probably timed out.")
async def close(self) -> None:
self.shut_down = True
await super().close()
if self.keychain_connection_task is not None:
await self.keychain_connection_task
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
async def get_response_for_request(self, request_name: str, data: Dict[str, Any]) -> Tuple[WsRpcMessage, bool]:
request = self.format_request(request_name, data)
response = await self._get(request)
success = response["data"].get("success", False)
return response, success
def handle_error(self, response: WsRpcMessage) -> None:
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
"""
Common error handling for RPC responses
"""
error = response["data"].get("error", None)
if error:
error_details = response["data"].get("error_details", {})
if error == KEYCHAIN_ERR_LOCKED:
raise KeychainIsLocked()
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
elif error == KEYCHAIN_ERR_NO_KEYS:
raise KeychainIsEmpty()
elif error == KEYCHAIN_ERR_KEY_NOT_FOUND:
raise KeychainKeyNotFound()
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
elif error == KEYCHAIN_ERR_MALFORMED_REQUEST:
message = error_details.get("message", "")
raise KeychainMalformedRequest(message)
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
else:
# Try to construct a more informative error message including the call that failed
if "command" in response["data"]:
err = f"{response['data'].get('command')} failed with error: {error}"
raise Exception(f"{err}")
raise Exception(f"{error}")
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
async def add_private_key(self, mnemonic: str, label: Optional[str] = None) -> PrivateKey:
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
"""
Forwards to Keychain.add_private_key()
"""
key: PrivateKey
if self.use_local_keychain():
key = self.keychain.add_private_key(mnemonic, label)
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
else:
response, success = await self.get_response_for_request(
"add_private_key", {"mnemonic": mnemonic, "label": label}
)
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
if success:
seed = mnemonic_to_seed(mnemonic)
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
key = AugSchemeMPL.key_gen(seed)
else:
error = response["data"].get("error", None)
if error == KEYCHAIN_ERR_KEYERROR:
error_details = response["data"].get("error_details", {})
word = error_details.get("word", "")
raise KeyError(word)
else:
self.handle_error(response)
return key
async def check_keys(self, root_path: Path) -> None:
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
"""
Forwards to init_funcs.check_keys()
"""
if self.use_local_keychain():
check_keys(root_path, self.keychain)
else:
response, success = await self.get_response_for_request("check_keys", {"root_path": str(root_path)})
if not success:
self.handle_error(response)
async def delete_all_keys(self) -> None:
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
"""
Forwards to Keychain.delete_all_keys()
"""
if self.use_local_keychain():
self.keychain.delete_all_keys()
else:
response, success = await self.get_response_for_request("delete_all_keys", {})
if not success:
self.handle_error(response)
async def delete_key_by_fingerprint(self, fingerprint: int) -> None:
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
"""
Forwards to Keychain.delete_key_by_fingerprint()
"""
if self.use_local_keychain():
self.keychain.delete_key_by_fingerprint(fingerprint)
else:
response, success = await self.get_response_for_request(
"delete_key_by_fingerprint", {"fingerprint": fingerprint}
)
if not success:
self.handle_error(response)
async def get_all_private_keys(self) -> List[Tuple[PrivateKey, bytes]]:
"""
Forwards to Keychain.get_all_private_keys()
"""
keys: List[Tuple[PrivateKey, bytes]] = []
if self.use_local_keychain():
keys = self.keychain.get_all_private_keys()
else:
response, success = await self.get_response_for_request("get_all_private_keys", {})
if success:
private_keys = response["data"].get("private_keys", None)
if private_keys is None:
err = f"Missing private_keys in {response.get('command')} response"
self.log.error(f"{err}")
raise KeychainMalformedResponse(f"{err}")
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
else:
for key_dict in private_keys:
pk = key_dict.get("pk", None)
ent_str = key_dict.get("entropy", None)
if pk is None or ent_str is None:
err = f"Missing pk and/or ent in {response.get('command')} response"
self.log.error(f"{err}")
continue # We'll skip the incomplete key entry
ent = bytes.fromhex(ent_str)
mnemonic = bytes_to_mnemonic(ent)
seed = mnemonic_to_seed(mnemonic)
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
key = AugSchemeMPL.key_gen(seed)
if bytes(key.get_g1()).hex() == pk:
keys.append((key, ent))
else:
err = "G1Elements don't match"
self.log.error(f"{err}")
else:
self.handle_error(response)
return keys
async def get_first_private_key(self) -> Optional[PrivateKey]:
"""
Forwards to Keychain.get_first_private_key()
"""
key: Optional[PrivateKey] = None
if self.use_local_keychain():
sk_ent = self.keychain.get_first_private_key()
if sk_ent:
key = sk_ent[0]
else:
response, success = await self.get_response_for_request("get_first_private_key", {})
if success:
private_key = response["data"].get("private_key", None)
if private_key is None:
err = f"Missing private_key in {response.get('command')} response"
self.log.error(f"{err}")
raise KeychainMalformedResponse(f"{err}")
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
else:
pk = private_key.get("pk", None)
ent_str = private_key.get("entropy", None)
if pk is None or ent_str is None:
err = f"Missing pk and/or ent in {response.get('command')} response"
self.log.error(f"{err}")
raise KeychainMalformedResponse(f"{err}")
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
ent = bytes.fromhex(ent_str)
mnemonic = bytes_to_mnemonic(ent)
seed = mnemonic_to_seed(mnemonic)
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
sk = AugSchemeMPL.key_gen(seed)
if bytes(sk.get_g1()).hex() == pk:
key = sk
else:
err = "G1Elements don't match"
self.log.error(f"{err}")
else:
self.handle_error(response)
return key
async def get_key_for_fingerprint(self, fingerprint: Optional[int]) -> Optional[PrivateKey]:
"""
Locates and returns a private key matching the provided fingerprint
"""
key: Optional[PrivateKey] = None
if self.use_local_keychain():
private_keys = self.keychain.get_all_private_keys()
if len(private_keys) == 0:
raise KeychainIsEmpty()
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
else:
if fingerprint is not None:
for sk, _ in private_keys:
if sk.get_g1().get_fingerprint() == fingerprint:
key = sk
break
if key is None:
raise KeychainKeyNotFound(fingerprint)
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
else:
key = private_keys[0][0]
else:
response, success = await self.get_response_for_request(
"get_key_for_fingerprint", {"fingerprint": fingerprint}
)
if success:
pk = response["data"].get("pk", None)
ent = response["data"].get("entropy", None)
if pk is None or ent is None:
err = f"Missing pk and/or ent in {response.get('command')} response"
self.log.error(f"{err}")
raise KeychainMalformedResponse(f"{err}")
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
else:
mnemonic = bytes_to_mnemonic(bytes.fromhex(ent))
seed = mnemonic_to_seed(mnemonic)
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
private_key = AugSchemeMPL.key_gen(seed)
if bytes(private_key.get_g1()).hex() == pk:
key = private_key
else:
err = "G1Elements don't match"
self.log.error(f"{err}")
else:
self.handle_error(response)
return key
async def get_key(self, fingerprint: int, include_secrets: bool = False) -> Optional[KeyData]:
"""
Locates and returns KeyData matching the provided fingerprint
"""
key_data: Optional[KeyData] = None
if self.use_local_keychain():
key_data = self.keychain.get_key(fingerprint, include_secrets)
else:
response, success = await self.get_response_for_request(
"get_key", {"fingerprint": fingerprint, "include_secrets": include_secrets}
)
if success:
key_data = KeyData.from_json_dict(response["data"]["key"])
else:
self.handle_error(response)
return key_data
async def get_keys(self, include_secrets: bool = False) -> List[KeyData]:
"""
Returns all KeyData
"""
keys: List[KeyData] = []
if self.use_local_keychain():
keys = self.keychain.get_keys(include_secrets)
else:
response, success = await self.get_response_for_request("get_keys", {"include_secrets": include_secrets})
if success:
keys = [KeyData.from_json_dict(key) for key in response["data"]["keys"]]
else:
self.handle_error(response)
return keys
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
def wrap_local_keychain(keychain: Keychain, log: logging.Logger) -> KeychainProxy:
"""
Wrap an existing local Keychain instance in a KeychainProxy to utilize
the same interface as a remote Keychain
"""
return KeychainProxy(local_keychain=keychain, log=log)
async def connect_to_keychain(
self_hostname: str,
daemon_port: int,
daemon_heartbeat: int,
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
ssl_context: Optional[ssl.SSLContext],
log: logging.Logger,
user: Optional[str] = None,
service: Optional[str] = None,
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
) -> KeychainProxy:
"""
Connect to the local daemon.
"""
client = KeychainProxy(
uri=f"wss://{self_hostname}:{daemon_port}",
heartbeat=daemon_heartbeat,
ssl_context=ssl_context,
log=log,
user=user,
service=service,
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
)
# Connect to the service if the proxy isn't using a local keychain
if not client.use_local_keychain():
await client.start()
return client
async def connect_to_keychain_and_validate(
macOS keyring.yaml support (#8292) * Added 'service' as a Keychain ctor param. Removed 'testing' * Detect existing keys in the Mac Keychain * Fix to allow migration of keys on macOS * Added dump_keyring.py tool to show decrypted contents of keyring.yaml * Prompt to save passphrase to macOS keychain * Master passphrase retrieval/removal from the macOS Keychain. Fixed typos. * Warn if errSecInteractionNotAllowed is detected when accessing the macOS Keychain * Fixed file_keyring synchronization test failures on macOS. Fixed sporadic test failures on macOS when fsevents are delivered for the keyring after deletion. TempKeyring-based tests now patch supports_os_passphrase_storage() to return False. * TempKeyring mocks-out legacy_keyring setup to allow tests to succeed on macOS (which could find existing keys in the Keychain) * Fixed pylint error * Use with_name instead of with_stem (which is new to Python 3.9) * Fixed keychain tests that started prompting for the keyring passphrase. * Fixed LGTM issues * Re-added the cleaning up temp keychain statement. This is being removed in a separate PR. * Linter fixes * Fixed keyring assignment on macOS when passphrase support is disabled. * Include 'can_save_passphrase' flag in keyring_status response * More linter fixes * Fixed determination of the user_passphrase_is_set flag. This was returning true for a newly created keyring without any keys (or passphrase set) * Removed the tidy_passphrase function per feedback * Added some comments based on feedback * Update chia/cmds/passphrase_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com>
2021-09-24 20:32:57 +03:00
root_path: Path,
log: logging.Logger,
user: Optional[str] = None,
service: Optional[str] = None,
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
) -> Optional[KeychainProxy]:
"""
Connect to the local daemon and do a ping to ensure that something is really
there and running.
"""
try:
net_config = load_config(root_path, "config.yaml")
crt_path = root_path / net_config["daemon_ssl"]["private_crt"]
key_path = root_path / net_config["daemon_ssl"]["private_key"]
ca_crt_path = root_path / net_config["private_ssl_ca"]["crt"]
ca_key_path = root_path / net_config["private_ssl_ca"]["key"]
ssl_context = ssl_context_for_client(ca_crt_path, ca_key_path, crt_path, key_path, log=log)
daemon_heartbeat = net_config.get("daemon_heartbeat", 300)
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
connection = await connect_to_keychain(
net_config["self_hostname"], net_config["daemon_port"], daemon_heartbeat, ssl_context, log, user, service
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
)
# If proxying to a local keychain, don't attempt to ping
if connection.use_local_keychain():
return connection
r = await connection.ping() # this is purposely using the base classes _get method
Keyring passphrase protection (#7249) * Moved keyring handling into a KeyringWrapper class * Update click to 8.0.x for prompt_required support * Renamed KeyringWrapper to _KeyringWrapper * Expose password management options on Linux * CLI support for setting/removing a password * Global option for specifying the master password * Cache the password instead of setting on the context * Password bootstrapping during chia init * Tidying up _KeyringWraper's interface * Initial pass migrating the legacy keyring contents * Encryption/decryption of keyring.yaml contents * FileKeyring backend encrypts with ChaCha20Poly1305 * Tightened up keyring migration and initialization * Fixed issues identified by linters * Remove root_path from Keychain * Prevent double-migration if setting master passwd * KeyringWrapper tests are mostly complete * FileKeyring will now honor the service param * Tests for get/set/delete password * Formatting/commenting updates * Writer lock support with tests - WIP * keyring.yaml is now watched for modifications * Reader/Writer lock for get/delete password * Fixed linter issues * Reader lock tests * Formatting update * Hook up CHIA_ROOT support for KeychainWrapper * Quick fix to address test failures * Fixed failures when existing legacy keyring exists * Fixed test failures caused by reusing the same temp dir * keyring.yaml now lives in ~/.chia_keys by default. Can be overridden with CHIA_KEYS_ROOT or --keys-root-path * Fixed migration failure when setting a password (not using the default) * KeyringWrapper now uses supports_keyring_password to determine if a FileKeyring should be used. Patched tests to work regardless of whether supports_keyring_password return False * The daemon now takes a --have-gui option that will prevent calling check_keys() during startup. If the keyring is locked, we want the GUI to prompt for the password. * Added is_keyring_locked RPC call * Added 'unlock_keyring' RPC command * Added KeychainProxy and KeychainServer to handle RPC messages related to keyring operations. WalletNode no longer directly accesses the Keychain class. * Turn on macOS support for testing keyring passwords * Fixed get_key_for_fingerprint to use the ocal keychain if the platform doesn't need to remotely access the daemon's keychain. Fixed key reconstruction when sent over RPC. * Farmer now accesses the keychain over RPC * Fixes for linter issues and some restructuring to support tests that use setup_nodes.py * Couple of fixes to unblock the GUI from launching when a keyring password is set * Added a keychain RPC call for add_private_key() * Added remaining keychain proxy RPC calls for delete_key_by_fingerprint and delete_all_keys * Check for None when inspecting request arguments * Run check_keys after unlocking the keyring when the daemon is launched via GUI * Added check_keys RPC method. Fixed deserialization of key entropy in get_all_private_keys. This was preventing the GUI from being able to show key details. * Added get_first_private_key to keychain_server/proxy. create_plots now uses the keychain proxy when launched from the daemon. * Added a comment about KeychainProxy in chia plots check * Workaround import conflict when importing from 'tests.*' due to fasteners name conflict * Simulator now uses KeychainProxy if launched by the daemon. KeychainServer/Proxy now takes keychain user/testing params for testing scenarios. * Added "set_keyring_passphrase" RPC message * Reworking KeychainProxy usage to handle local keychain tests and RPC keychain tests. * Replace my prior usage of asyncio.run() with asyncio.get_event_loop().run_until_complete() * Silencing file_keyring logging for the moment. * Updated tests to use test keychains and appropriate BlockTools construction BlockTools should now be created with create_block_tools(_async) to handle async scenarios. Updated block_tools to be async compatible Updated fasteners to fix installation of top-level 'tests' in site-packages * Added 'remove_keyring_passphrase' RPC message to the daemon Minor tweak to TempKeyring to default to some test params * Fixed linter issues * Remove flake8 ignore statement now that the fasteners module has been updated * Some initial renaming changes: password -> passphrase * Fixed wallet RPC issue where get_key_for_fingerprint wasn't awaited-upon. Fixed legacy keyring initialization (for migration scenarios) * Fixed improperly merged file * Fixed linter issues. More renaming. * Updated spots that were still using an incorrect keychain call * Renamed use_password_cache, obtain_current_password * Renamed supports_keyring_password * Renamed has_master_password * Renamed has_cached_password, get_cached_master_password * Linter fixes * Renamed master_password_is_valid * Renamed set_cached_master_password * Renamed set_master_password * Renamed remove_master_password * Renamed has_cached_master_password * Renaming in file_keyring and keyring_wrapper Updated default keyring payload used for tests * Renamed get_password Other renaming updates * Renamed set_password Other renaming updates * Renamed remaining password occurrences (where appropriate) * password -> passphrase * Added tests for setting an emoji and Japanese master passphrase * Attempt to notify the daemon when a keyring passphrase is set/updated/removed * Missed one password -> passphrase replacement. * Fixed some file synchronization issues found when running tests on macOS * Adjusted timeout values for test_writer_lock_reacquisition_failure for macOS. * Removed logging statements previously added for debugging * Prompt for keyring passphrase up-front when launching a service. Changed --have-gui flag to --wait-for-unlock * Updated set_keyring_passphrase RPC message to fix optional current_passphrase param when the keyring is using the default passphrase. * Minor test cleanup to deduplicate some code. * Fixed regression when setting a new master passphrase * Minor refactoring and docs/commenting updates * Renaming password -> passphrase went too far. Keyring backends use password terminology for compatibility with third party backends. * Disabling macOS support (previously added for testing only) * Disabling passphrase support in preparation for sending out the PR * Fixed improper merge (vscode didn't save changes during rebase) * Update chia/cmds/init_funcs.py Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> * skip_check_keys -> should_check_keys * Shuffling some imports around to break cycles reported by LGTM * Handle unlocking the daemon if it's already launched and waiting for unlock. * Replaced uses_keychain_proxy decorator in farmer.py. Fixed async usage of get_reward_targets. Linter/reformatting fixes * Replaced uses_keychain_proxy decorator with a clearer method. * Cleanup the temp keyring dir using shutil.rmtree() * Restored self._root_path (had been changed to self.root_path) * Minor cleanup * ensure_keychain_proxy() now throws if connect_to_keychain_and_validate() fails * Plot key resolution now yields a PlotKeys object which can be passed into create_plots. De-indented test_invalid_icc_sub_slot_vdf to keep git blame tidy. * Added 'keyring_status' daemon RPC message to support the GUI * Minor changes relating to PR feedback * Addressed more PR feedback (mostly type annotations) * Commented-out macOS file keyring usage. This can be re-enabled for testing purposes. * Addressed test failures that require multiple keyrings in the same process. Each TempKeyring will now set a custom KeyringWrapper instance. * Fixed logic for communicating user_passphrase_is_set in the keyring_status RPC response. * Updated type annotations and method signature for set_passphrase to expect a string instead of bytes. * Fixed Wallet RPC tests * Fixed full_node_store tests. BlockTools should be created using the create_block_tools(_async) function(s) * Fixed test failures in test_pool_rpc * Fixed test_daemon. After BlockTools.setup_plots is run, the config file needs to be re-read to refresh stale plot_directories. * Suppressing LGTM false positives regarding passphrase leakage in CLI error output. Seems that LGTM sees MIN_PASSPHRASE_LEN as sensitive data. * Second attempt at suppressing LGTM false positives * Third attempt at addressing LGTM false positives * Removed test_keyring_wrapper param from Keychain ctor. Test setup now sets the keyring_wrapper property directly. * Reformatting * More targeted update of the test config to refresh just the "plot_directories" value * More LGTM suppressions Co-authored-by: Adam Kelly <338792+aqk@users.noreply.github.com> Co-authored-by: wjblanke <wjb98672@gmail.com>
2021-08-04 22:46:55 +03:00
if "value" in r["data"] and r["data"]["value"] == "pong":
return connection
except Exception as e:
print(f"Keychain(daemon) not started yet: {e}")
return None