Skip to content

Commit

Permalink
feat(python): make failing to resume session hard-fail
Browse files Browse the repository at this point in the history
  • Loading branch information
M1nd3r committed Mar 6, 2025
1 parent 45869b0 commit 55937b6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
15 changes: 12 additions & 3 deletions python/src/trezorlib/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,12 @@ def get_session(
if must_resume:
if session.id != self.session_id or session.id is None:
click.echo("Failed to resume session")
RuntimeError("Failed to resume session - no session id provided")
env_var = os.environ.get("TREZOR_SESSION_ID")
if env_var and bytes.fromhex(env_var) == self.session_id:
click.echo(
"Session-id stored in TREZOR_SESSION_ID is no longer valid. Call 'unset TREZOR_SESSION_ID' to clear it."
)
raise exceptions.FailedSessionResumption()
return session

features = client.protocol.get_features()
Expand Down Expand Up @@ -265,6 +270,8 @@ def session_context(
except transport.DeviceIsBusy:
click.echo("Device is in use by another process.")
sys.exit(1)
except exceptions.FailedSessionResumption:
sys.exit(1)
except Exception:
click.echo("Failed to find a Trezor device.")
if self.path is not None:
Expand Down Expand Up @@ -306,17 +313,19 @@ def decorator(
def function_with_session(
obj: TrezorConnection, *args: "P.args", **kwargs: "P.kwargs"
) -> "R":
is_resume_mandatory = must_resume or obj.session_id is not None

with obj.session_context(
empty_passphrase=empty_passphrase,
derive_cardano=derive_cardano,
seedless=seedless,
must_resume=must_resume,
must_resume=is_resume_mandatory,
) as session:
try:
return func(session, *args, **kwargs)

finally:
if not must_resume:
if not is_resume_mandatory:
session.end()

return function_with_session
Expand Down
7 changes: 7 additions & 0 deletions python/src/trezorlib/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,10 @@ def __init__(self, expected: type[MessageType], actual: MessageType) -> None:
self.expected = expected
self.actual = actual
super().__init__(f"Expected {expected.__name__} but Trezor sent {actual}")


class FailedSessionResumption(TrezorException):
"""Provided session_id is not valid / session cannot be resumed.
Raised when `trezorctl -s <sesssion_id>` is used or `TREZOR_SESSION_ID = <session_id>`
is set and resumption of session with the `session_id` fails."""

0 comments on commit 55937b6

Please sign in to comment.