1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-18 04:18:10 +00:00

python/trezorctl: make use of EndSession

This commit is contained in:
matejcik 2020-08-26 16:01:58 +02:00 committed by matejcik
parent e0ec5aa1e7
commit e96a9e8d39
3 changed files with 72 additions and 23 deletions

View File

@ -16,6 +16,7 @@
import functools import functools
import sys import sys
from contextlib import contextmanager
import click import click
@ -61,25 +62,59 @@ class TrezorConnection:
ui = self.get_ui() ui = self.get_ui()
return TrezorClient(transport, ui=ui, session_id=self.session_id) return TrezorClient(transport, ui=ui, session_id=self.session_id)
@contextmanager
def client_context(self):
"""Get a client instance as a context manager. Handle errors in a manner
appropriate for end-users.
def with_client(func): Usage:
@click.pass_obj >>> with obj.client_context() as client:
@functools.wraps(func) >>> do_your_actions_here()
def trezorctl_command_with_client(obj, *args, **kwargs): """
try: try:
client = obj.get_client() client = self.get_client()
except Exception: except Exception:
click.echo("Failed to find a Trezor device.") click.echo("Failed to find a Trezor device.")
if obj.path is not None: if self.path is not None:
click.echo("Using path: {}".format(obj.path)) click.echo("Using path: {}".format(self.path))
sys.exit(1) sys.exit(1)
try: try:
return func(client, *args, **kwargs) yield client
except exceptions.Cancelled: except exceptions.Cancelled:
# handle cancel action
click.echo("Action was cancelled.") click.echo("Action was cancelled.")
sys.exit(1) sys.exit(1)
except exceptions.TrezorException as e: except exceptions.TrezorException as e:
# handle any Trezor-sent exceptions as user-readable
raise click.ClickException(str(e)) from e raise click.ClickException(str(e)) from e
# other exceptions may cause a traceback
def with_client(func):
"""Wrap a Click command in `with obj.client_context() as client`.
Sessions are handled transparently. The user is warned when session did not resume
cleanly. The session is closed after the command completes - unless the session
was resumed, in which case it should remain open.
"""
@click.pass_obj
@functools.wraps(func)
def trezorctl_command_with_client(obj, *args, **kwargs):
with obj.client_context() as client:
session_was_resumed = obj.session_id == client.session_id
if not session_was_resumed and obj.session_id is not None:
# tried to resume but failed
click.echo("Warning: failed to resume session.", err=True)
try:
return func(client, *args, **kwargs)
finally:
if not session_was_resumed:
try:
client.end_session()
except Exception:
pass
return trezorctl_command_with_client return trezorctl_command_with_client

View File

@ -159,7 +159,7 @@ def configure_logging(verbose: int):
def cli(ctx, path, verbose, is_json, passphrase_on_host, session_id): def cli(ctx, path, verbose, is_json, passphrase_on_host, session_id):
configure_logging(verbose) configure_logging(verbose)
if session_id: if session_id is not None:
try: try:
session_id = bytes.fromhex(session_id) session_id = bytes.fromhex(session_id)
except ValueError: except ValueError:
@ -216,6 +216,11 @@ def list_devices(no_resolve):
for transport in enumerate_devices(): for transport in enumerate_devices():
client = TrezorClient(transport, ui=ui.ClickUI()) client = TrezorClient(transport, ui=ui.ClickUI())
click.echo("{} - {}".format(transport, format_device_name(client.features))) click.echo("{} - {}".format(transport, format_device_name(client.features)))
try:
# firmwares <2.3.4 do not recognize EndSession
client.end_session()
except Exception:
pass
@cli.command() @cli.command()
@ -241,8 +246,8 @@ def ping(client, message, button_protection):
@cli.command() @cli.command()
@with_client @click.pass_obj
def get_session(client): def get_session(obj):
"""Get a session ID for subsequent commands. """Get a session ID for subsequent commands.
Unlocks Trezor with a passphrase and returns a session ID. Use this session ID with Unlocks Trezor with a passphrase and returns a session ID. Use this session ID with
@ -252,13 +257,16 @@ def get_session(client):
The session ID is valid until another client starts using Trezor, until the next The session ID is valid until another client starts using Trezor, until the next
get-session call, or until Trezor is disconnected. get-session call, or until Trezor is disconnected.
""" """
from ..btc import get_address # make sure session is not resumed
from ..client import PASSPHRASE_TEST_PATH obj.session_id = None
with obj.client_context() as client:
if client.features.model == "1" and client.version < (1, 9, 0): if client.features.model == "1" and client.version < (1, 9, 0):
raise click.ClickException("Upgrade your firmware to enable session support.") raise click.ClickException(
"Upgrade your firmware to enable session support."
)
get_address(client, "Testnet", PASSPHRASE_TEST_PATH) client.ensure_unlocked()
if client.session_id is None: if client.session_id is None:
raise click.ClickException("Passphrase not enabled or firmware too old.") raise click.ClickException("Passphrase not enabled or firmware too old.")
else: else:

View File

@ -88,9 +88,9 @@ class TrezorClient:
LOG.info("creating client instance for device: {}".format(transport.get_path())) LOG.info("creating client instance for device: {}".format(transport.get_path()))
self.transport = transport self.transport = transport
self.ui = ui self.ui = ui
self.session_id = session_id
self.session_counter = 0 self.session_counter = 0
self.init_device() self.session_id = session_id
self.init_device(session_id=session_id)
def open(self): def open(self):
if self.session_counter == 0: if self.session_counter == 0:
@ -294,6 +294,11 @@ class TrezorClient:
if not isinstance(resp, messages.Features): if not isinstance(resp, messages.Features):
raise exceptions.TrezorException("Unexpected response to Initialize") raise exceptions.TrezorException("Unexpected response to Initialize")
if resp.session_id == self.session_id:
LOG.info("Successfully resumed session")
elif session_id is not None:
LOG.info("Failed to resume session")
# TT < 2.3.0 compatibility: # TT < 2.3.0 compatibility:
# _refresh_features will clear out the session_id field. We want this function # _refresh_features will clear out the session_id field. We want this function
# to return its value, so that callers can rely on it being either a valid # to return its value, so that callers can rely on it being either a valid
@ -385,6 +390,7 @@ class TrezorClient:
The session will become invalid until `init_device()` is called again. The session will become invalid until `init_device()` is called again.
If passphrase is enabled, further actions will prompt for it again. If passphrase is enabled, further actions will prompt for it again.
""" """
# since: 2.3.4, 1.9.4
self.call(messages.EndSession()) self.call(messages.EndSession())
self.session_id = None self.session_id = None
@ -400,4 +406,4 @@ class TrezorClient:
# call LockDevice manually to save one refresh_features() call # call LockDevice manually to save one refresh_features() call
self.call(messages.LockDevice()) self.call(messages.LockDevice())
self.end_session() self.end_session()
self.init_device() self.init_device(new_session=True)